<template>
  <div class="import-result-container">
    <div class="top-bar">
      <el-button
        size="small"
        icon="el-icon-download"
        @click="handleDownloadTemp"
      >下载模板</el-button>
      <el-tooltip
        class="item"
        effect="dark"
        placement="bottom-start"
      >
        <div
          slot="content"
          class="tips-content"
        >
          1.红色为必填信息<br />
          2.各行列顺序不可调整,请严格按照模板信息填写<br />
          3.如果需导入信息超出模板范围,请联系公司工作人员
        </div>
        <i class="el-icon-question tips"></i>
      </el-tooltip>
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="baseUrl+'/general-import/preDetection'"
        :data="{ treeId: templateTreeId }"
        :headers="{Authorization:token}"
        :auto-upload="false"
        :on-change="handleUploadChange"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        accept=".xlsx,.xls"
        :limit="1"
        :show-file-list="false"
        :on-exceed="handleExceed"
      >
        <div class="file-content">
          <span
            class="file-name"
            :title="fileName"
          >{{ fileName }}</span>
          <i
            v-show="fileName"
            class="close-icon el-icon-close"
            @click.stop="handleClearFiles"
          ></i>
          <i class="upload-icon el-icon-upload2"></i>
        </div>
      </el-upload>
      <div class="right">
        <el-button
          v-if="importStatus===import_status.PREDETECTING"
          size="small"
          type="primary"
          icon="el-icon-refresh"
          @click="handleStopPreDetection"
        >停止预检测</el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-refresh"
          :disabled="importStatus===import_status.PREDETECTING"
          @click="handlePreDetection"
        >预检测</el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-s-release"
          :disabled="predetectInterfaceFaild || ![import_status.PREDETECTFAILD,import_status.IMPORTFAILD].includes(importStatus)"
          @click="handleExportError"
        >错误信息导出</el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-upload"
          :disabled="importStatus !== import_status.PREDETECTSUCCESS"
          @click="handleImportDatabase"
        >导入数据库</el-button>
      </div>
    </div>
    <div :class="['result-content']">
      <div
        v-show="importStatus === import_status.PREDETECTING"
        class="result-content-num"
      >
        <i class="el-icon-loading"></i>
        正在检测中，请稍后
      </div>
      <div
        v-show="importStatus === import_status.IMPORTING"
        class="result-content-num"
      >
        <i class="el-icon-loading"></i>
        正在导入，请稍后
      </div>
      <div :class="['result-content-table', `importStatus-${importStatus}`]">
        <el-table
          ref="Table"
          :data="tableData"
          stripe
          border
          tooltip-effect="dark"
          style="width: 100%"
          height="calc(100% - 50px - 15px)"
        >
          <el-table-column
            prop="error"
            label="名称"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="日期"
            show-overflow-tooltip
          >
          </el-table-column>
          <!-- <el-table-column
            prop="status"
            label="状态"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="information"
            label="信息"
            show-overflow-tooltip
          >
          </el-table-column> -->
        </el-table>
        <div class="pagination">
          <pagination
            v-show="pager.total>0"
            :total="pager.total"
            :page.sync="pager.pageNum"
            :limit.sync="pager.pageSize"
            @pagination="getTableData"
          />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  downloadTemplateFile,
  importToDatabase,
  getErrorInfos,
  getImportingInfo,
  exportErrorInfos
} from '@/api/import/importing'
import { downloadFile } from '@/utils/file'
import { IMPORT_STATUS, TIPS, NODE_TYPE } from '../enum'
import service from '@/utils/request'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/eam'
export default {
  props: {
    data: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      fileList: [],
      tableData: [],
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      timer: null,
      importStatus: IMPORT_STATUS.INITIAL,
      predetectInterfaceFaild: false,
      startPredetect: false
    }
  },
  computed: {
    fileName() {
      if (!this.fileList.length) {
        return ''
      }
      return this.fileList[0].name
    },
    templateTreeId() {
      if (this.data?.nodeType !== NODE_TYPE.TEMPLATE) {
        return ''
      }
      return this.data?.id || ''
    },
    import_status() {
      return IMPORT_STATUS
    },
    node_type() {
      return NODE_TYPE
    },
    baseUrl() {
      return service.baseURL
    },
    token() {
      return 'Bearer ' + getToken()
    }
  },
  methods: {
    // 下载模板
    handleDownloadTemp() {
      downloadTemplateFile(this.data.id).then((res) => {
        downloadFile(
          res.file,
          `${this.data.name}导入模板${parseTime(new Date(), '{y}{m}{d}')}.xls`
        )
      })
    },
    handleExceed(files) {
      if (this.fileList[0] && files[0]) {
        files[0].uid = this.fileList[0].uid
        this.fileList[0].raw = files[0]
        this.fileList[0].name = files[0].name
      }
    },
    handleUploadChange(file) {
      this.fileList = [file]
    },
    handleUploadSuccess(response) {
      if (response?.code === 200) {
        this.handleRoundTimer()
      } else {
        this.$message({ type: 'error', message: response.msg })
        this.importStatus = IMPORT_STATUS.PREDETECTFAILD
      }
    },
    handleUploadError(error) {
      if (!error?.message) {
        this.$message.error('接口异常')
        this.$nextTick(() => {
          this.importStatus = IMPORT_STATUS.PREDETECTFAILD
          this.predetectInterfaceFaild = true
          this.handleClearFiles()
        })
        return
      }
      let message = JSON.parse(error.message).exception
      if (message == 'Network Error') {
        message = '后端接口连接异常'
      } else if (message.includes('timed out')) {
        message = '系统接口请求超时'
      } else if (message.includes('Request failed with status code')) {
        message = '系统接口' + message.substr(message.length - 3) + '异常'
      }
      this.$message({ type: 'error', message: message })
      this.$nextTick(() => {
        this.importStatus = IMPORT_STATUS.PREDETECTFAILD
        this.predetectInterfaceFaild = true
        this.handleClearFiles()
      })
    },
    handleClearFiles() {
      this.$refs.upload?.clearFiles()
      this.fileList = []
    },
    // 获取错误列表数据（预检测后显示）
    getTableData() {
      if (!this.templateTreeId) {
        return
      }
      const { pageNum, pageSize } = this.pager
      getErrorInfos(this.templateTreeId, pageNum, pageSize).then((res) => {
        this.tableData = res.data.records
        this.pager.total = res.data.total
      })
    },
    // 错误信息导出
    handleExportError() {
      if (!this.templateTreeId) {
        return
      }
      exportErrorInfos(this.templateTreeId).then((res) => {
        downloadFile(
          res.file,
          `${this.data.name}_错误信息${parseTime(new Date(), '{y}{m}{d}')}.xls`
        )
      })
    },
    // 预检测
    handlePreDetection() {
      if (
        !this.templateTreeId ||
        this.importStatus === IMPORT_STATUS.PREDETECTING
      ) {
        return
      }
      if (!this.fileList?.length) {
        this.$message.warning('请选择检测文件')
        return
      }
      if (
        this.fileList?.length &&
        ['success', 'fail'].includes(this.fileList[0].status)
      ) {
        this.fileList[0].status = 'ready'
        this.fileList[0].percentage = 0
        delete this.fileList[0].response
      }
      this.startPredetect = true
      this.$refs.upload.submit()
      this.importStatus = IMPORT_STATUS.PREDETECTING
    },
    // 停止预检测
    handleStopPreDetection() {
      this.importStatus = IMPORT_STATUS.INITIAL
      this.stopRoundTimer()
      this.$refs.upload?.abort()
      // this.handleClearFiles()
      this.$message.success('预检测已停止')
    },
    // 导入数据库
    handleImportDatabase() {
      if (!this.templateTreeId) {
        return
      }
      importToDatabase(this.templateTreeId)
        .then((res) => {
          this.handleRoundTimer()
        })
        .catch(() => {
          this.handleRoundTimer()
        })
      this.importStatus = IMPORT_STATUS.IMPORTING
    },
    // 获取预检测状态
    async getImportStatus() {
      if (!this.templateTreeId) {
        return
      }
      const res = await getImportingInfo(this.templateTreeId)
      this.importStatus = res.data.importStatus
      if (
        [
          IMPORT_STATUS.PREDETECTFAILD,
          IMPORT_STATUS.IMPORTFAILD,
          IMPORT_STATUS.IMPORTSUCCESS
        ].includes(res.data?.importStatus)
      ) {
        this.getTableData()
      } else {
        this.tableData = []
        this.pager.total = 0
      }
      // 预检测成功和导入数据库成功都提示
      if (this.startPredetect) {
        switch (res.data.importStatus) {
          case IMPORT_STATUS.PREDETECTSUCCESS:
            this.$message.success(TIPS.PREDETECTSUCCESS)
            break
          case IMPORT_STATUS.IMPORTSUCCESS:
            this.$message.success(TIPS.IMPORTSUCCESS)
            break
        }
      }

      return Promise.resolve(res.data.importStatus)
    },
    // 轮询查询预检测状态
    async handleRoundTimer() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      const importStatus = await this.getImportStatus()
      if (
        [IMPORT_STATUS.PREDETECTING, IMPORT_STATUS.IMPORTING].includes(
          importStatus
        )
      ) {
        this.timer = setTimeout(() => {
          this.handleRoundTimer()
        }, 3000)
      } else {
        this.stopRoundTimer()
      }
      // 导入完成
      if (importStatus === IMPORT_STATUS.IMPORTSUCCESS) {
        this.handleClearFiles()
      }
    },
    // 停止轮询
    stopRoundTimer() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
    }
  },
  watch: {
    data: {
      handler(newVal, oldVal) {
        if (
          !newVal ||
          newVal.nodeType !== NODE_TYPE.TEMPLATE ||
          newVal.id === oldVal?.id
        ) {
          return
        }
        this.startPredetect = false
        this.handleClearFiles()
        this.handleRoundTimer()
      },
      immediate: true
    }
  },
  destroyed() {
    this.stopRoundTimer()
  }
}
</script>
<style lang="scss" scoped>
@import "../../../assets/styles/element-variables";

.import-result-container {
  height: 100%;

  .top-bar {
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #dcdfe6;

    .right {
      float: right;
    }
  }

  .tips {
    margin: 0 10px;
    // color: $--color-primary;
    font-size: 16px;
  }

  .upload-demo {
    display: inline-block;
    vertical-align: middle;
  }

  .file-content {
    padding-left: 10px;
    color: #606266;
    width: 240px;
    height: 32px;
    line-height: 32px;
    border: 1px solid rgb(220, 223, 230);
    border-radius: 3px;
    vertical-align: middle;
    display: flex;
    .close-icon {
      line-height: 32px;
      display: none;
    }
    &:hover {
      .close-icon {
        display: inline-block;
      }
    }
  }

  .file-name {
    display: inline-block;
    width: calc(100% - 26px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: left;
  }

  .upload-icon {
    padding: 0 10px;
    line-height: 32px;
    // color: $--color-primary;
    cursor: pointer;
  }

  .result-content {
    height: calc(100% - 56px);

    &-num {
      height: 60px;
      text-align: center;
      line-height: 60px;
    }

    &-table {
      height: calc(100%);

      &.importStatus-1,
      &.importStatus-4 {
        height: calc(100% - 60px);
      }
    }
  }

  .pagination {
    overflow: hidden;
    .pagination-container {
      margin-bottom: 0;
    }
  }
}
</style>
<style lang="scss">
.tips-content {
  font-size: 13px;
  line-height: 22px;
}
</style>